package cn.weekdragon.gscore.adapter.service;

import cn.weekdragon.gscore.adapter.bot.WsReverseBot;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public abstract class WsReverseService extends AbstractService{

    private volatile boolean firstConnected = true;
    /**
     * 反向链接的地址
     */
    protected String wsReverse;

    /**
     * authorization，连接授权
     */
    protected String authorization;

    protected WebSocketClient wsClient;

    public WsReverseService(String wsReverse, String serviceName, String authorization) throws URISyntaxException {
        this.wsReverse = wsReverse;
        this.authorization = authorization;
        this.serviceName = serviceName;
        this.wsClient = new WebSocketClient(new URI(wsReverse)) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                WsReverseService.this.onOpen(handshakedata);
            }

            @Override
            public void onMessage(String message) {
                WsReverseService.this.onMessage(message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                WsReverseService.this.onClose(code,reason,remote);
            }

            @Override
            public void onError(Exception ex) {
                WsReverseService.this.onError(ex);
            }

            @Override
            public void onMessage(ByteBuffer bytes) {
                onMessage(StandardCharsets.UTF_8.decode(bytes).toString());
            }
        };

    }

    @Override
    public void reconnect() {
        if(firstConnected){
            this.wsClient.connect();
            firstConnected = false;
            return;
        }
        if(this.wsClient.isOpen()){
            return;
        }
        this.wsClient.reconnect();
    }

    public void onOpen(ServerHandshake handshakedata){
        ServiceManager.addService(this);
    }

    public void onMessage(String message){

    }

    public void onClose(int code, String reason, boolean remote){

    }

    public void onError(Exception ex){

    }



}
